"""
@description: Utils class about OSS related operations.
@author: Zzay
@create: 2022/07/14
"""
import oss2
import os
import csv
import shutil
from itertools import islice

# config
ACCESS_KEY_ID = "LTAI5tKePUvpaVznqtbxTvfW"
ACCESS_KEY_SECRET = "QPIjzj6YxMGAhzAiF0G3umoZZwmQ8X"

BUCKET_ENDPOINT = "http://oss-cn-shenzhen.aliyuncs.com/"
BUCKET_NAME = "zzay"

# oss
auth = oss2.Auth(ACCESS_KEY_ID, ACCESS_KEY_SECRET)
bucket = oss2.Bucket(auth, BUCKET_ENDPOINT, BUCKET_NAME)


def oss_upload(path):
    """
    Upload file to OSS.
    :param path: Path of the directory that contains files to be uploaded
    """
    file_path_list = []
    file_name_list = []

    # enumerate all the files in the given directory
    for file in os.listdir(path):
        # if it's a file, then append it to the list
        file_path = os.path.join(path, file)
        if os.path.isfile(file_path):
            file_path_list.append(file_path)
            file_name_list.append(file)

    print(file_path_list)
    print(file_name_list)

    for path in file_path_list:
        path = path.split('\\')[6]

    for i in range(len(file_path_list)):
        with open(file_path_list[i], "rb") as file_obj:
            file_obj.seek(0, os.SEEK_SET)
            current = file_obj.tell()
            bucket.put_object(path + "/" + file_name_list[i], file_obj)


def oss_upload_model(path, version_path):
    auth = oss2.Auth('LTAI5t7F4EknEEwsvX7vTt3d', 'GDiOCB362FNZZHa1EqUPVaF42I5dEg')
    # Endpoint以杭州为例，其它Region请按实际情况填写。
    bucket = oss2.Bucket(auth, 'http://oss-cn-beijing.aliyuncs.com/', 'zzay')
    with open(path, 'rb') as fileobj:
        # Seek方法用于指定从第1000个字节位置开始读写。上传时会从您指定的第1000个字节位置开始上传，直到文件结束。
        fileobj.seek(0, os.SEEK_SET)
        # Tell方法用于返回当前位置。
        current = fileobj.tell()
        bucket.put_object(path, fileobj)
    with open(version_path, 'rb') as fileobj:
        # Seek方法用于指定从第1000个字节位置开始读写。上传时会从您指定的第1000个字节位置开始上传，直到文件结束。
        fileobj.seek(0, os.SEEK_SET)
        # Tell方法用于返回当前位置。
        current = fileobj.tell()
        bucket.put_object(version_path, fileobj)


def oss_download(remote_file, local_file):
    auth = oss2.Auth('LTAI5t7F4EknEEwsvX7vTt3d', 'GDiOCB362FNZZHa1EqUPVaF42I5dEg')
    # Endpoint以杭州为例，其它Region请按实际情况填写。
    bucket = oss2.Bucket(auth, 'http://oss-cn-beijing.aliyuncs.com/', 'lzh-pic')
    # if_access_bucket = oss2.Bucket(self.auth, config['OSS_CONFIG']['endpoint'],'if-access')
    local_path = os.path.dirname(local_file)
    if local_path and not os.path.exists(local_path):
        os.makedirs(local_path)

    res = bucket.get_object_to_file(remote_file, local_file)
    return res


def oss_download_image():
    auth = oss2.Auth('LTAI5t7F4EknEEwsvX7vTt3d', 'GDiOCB362FNZZHa1EqUPVaF42I5dEg')
    # Endpoint以杭州为例，其它Region请按实际情况填写。
    bucket = oss2.Bucket(auth, 'http://oss-cn-beijing.aliyuncs.com/', 'lzh-pic')
    # if_access_bucket = oss2.Bucket(self.auth, config['OSS_CONFIG']['endpoint'],'if-access')
    if os.path.exists('images/oldpeople'):
        shutil.rmtree('images/oldpeople', True)
    os.mkdir('images/oldpeople')
    if os.path.exists('images/volunteer'):
        shutil.rmtree('images/volunteer', True)
    os.mkdir('images/volunteer')
    if os.path.exists('images/employee'):
        shutil.rmtree('images/employee', True)
    os.mkdir('images/employee')

    data = [
        ("id_card", "name", "type"),
        ("Unknown", "陌生人", ""),
    ]
    f = open('info/people_info.csv', 'w')
    writer = csv.writer(f)

    for b in islice(oss2.ObjectIterator(bucket, prefix='images/oldpeople'), 1000):
        if b.key.endswith('/'):
            print('directory: ', b.key)
            isExists = os.path.exists(b.key)
            if not isExists:
                os.makedirs(b.key)
                print(b.key, '创建成功')
        else:
            if not os.path.exists(os.path.split(b.key)[0]):
                path = os.path.split(b.key)[0]
                os.makedirs(path)
                str_temp = path.split('/')
                data_item = (
                    str_temp.__getitem__(len(str_temp) - 1), str_temp.__getitem__(len(str_temp) - 1), "old_people")
                data.append(data_item)
                print(os.path.split(b.key)[0], '创建成功')
            print("downloadfile-->", b.key)
            bucket.get_object_to_file(b.key, b.key)
    for b in islice(oss2.ObjectIterator(bucket, prefix='images/volunteer'), 1000):
        if b.key.endswith('/'):
            print('directory: ', b.key)
            isExists = os.path.exists(b.key)
            if not isExists:
                os.makedirs(b.key)
                print(b.key, '创建成功')
        else:
            if not os.path.exists(os.path.split(b.key)[0]):
                path = os.path.split(b.key)[0]
                os.makedirs(path)
                str_temp = path.split('/')
                data_item = (
                    str_temp.__getitem__(len(str_temp) - 1), str_temp.__getitem__(len(str_temp) - 1), "volunteer")
                data.append(data_item)
                print(os.path.split(b.key)[0], '创建成功')
            print("downloadfile-->", b.key)
            bucket.get_object_to_file(b.key, b.key)
    for b in islice(oss2.ObjectIterator(bucket, prefix='images/employee'), 1000):
        if b.key.endswith('/'):
            print('directory: ', b.key)
            isExists = os.path.exists(b.key)
            if not isExists:
                os.makedirs(b.key)
                print(b.key, '创建成功')
        else:
            if not os.path.exists(os.path.split(b.key)[0]):
                path = os.path.split(b.key)[0]
                os.makedirs(path)
                str_temp = path.split('/')
                data_item = (
                    str_temp.__getitem__(len(str_temp) - 1), str_temp.__getitem__(len(str_temp) - 1), "employee")
                data.append(data_item)
                print(os.path.split(b.key)[0], '创建成功')
            print("downloadfile-->", b.key)
            bucket.get_object_to_file(b.key, b.key)

    for i in data:
        writer.writerow(i)
    f.close()
